package com.spzx.product.handler;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.spzx.product.api.domain.Category;
import com.spzx.product.service.CategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CategoryExcelDateReadListener extends AnalysisEventListener<Category> {
    private final List<Category> categoryList = new ArrayList<>();

    @Resource
    private CategoryService categoryService;

    @Override
    public void invoke(Category category, AnalysisContext analysisContext) {
        int limit = 100;
        if (categoryService.checkCategoryUnique(category)) {
            // 如果数据库中已经存在该分类，则不保存
            return;
        }
        categoryList.add(category);
        if (categoryList.size() >= limit) {
            categoryService.saveBatch(categoryList);
            categoryList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (categoryList.size() > 0) {
            categoryService.saveBatch(categoryList);
            categoryList.clear();
        }
    }
}
